let proxyTarget = 'http://127.0.0.1:8933',
socketTarget = 'ws://127.0.0.1:13020';

if (process.env.WebpackProxyTarget) {
  proxyTarget = `${process.env.WebpackProxyTarget}`;
}

if (process.env.WebpackSocketIOTarget) {
  socketTarget = process.env.WebpackSocketIOTarget;
}

const PROXY_MAPS = {
  '/api/system': proxyTarget,
  '/api': proxyTarget,
  '/socket.io': socketTarget
};

const PROXY_APPEND = {
  '/socket.io': {
    ws: true
  }
};

const HOST = '127.0.0.1';
const VERSION = 'v0.0.1';
const ENABLE_REDUX_LOG = false;
const path = require('path');
const webpack = require('webpack');
const pathConfig = require('./pathConfig');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackMock = require('webpack-api-mocker');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const modifyVars = require('./modifyVars');
const DEPLOY_TIME = Date.now();

if (process.env.MOCK) {
  console.log('> 使用MOCK数据\r\n');
} else {
  console.log(`> 使用接口数据\r\n`);
}

console.log('> 代理接口:');
Object.keys(PROXY_MAPS).forEach(key => console.log(`>  ${key}: ${PROXY_MAPS[key]}`));

console.log(`> 开启redux日志: ${ENABLE_REDUX_LOG} \r\n`);

const devServerSource = process.env.MOCK
  ? {
    before (app) {
      webpackMock(app, path.resolve(__dirname, '../__mock__/index.js'));
    }
  }
  : {
    proxy: Object.keys(PROXY_MAPS).reduce((total, curr) => {
      total[curr] = {
        target: PROXY_MAPS[curr],
        changeOrigin: true,
        secure: false,
        ...(PROXY_APPEND[curr] || {})
      };
      return total;
    }, {})
  };

module.exports = {
  mode: 'development',
  entry: {
    app: pathConfig.appIndexJs,
    updating: pathConfig.appUpdating
  },
  output: {
    publicPath: '/',
    path: pathConfig.appBuild,
    filename: 'static/js/[name].js',
    chunkFilename: 'static/js/[name].chunk.js'
  },
  resolve: {
    extensions: ['.js'],
    alias: require('./alias'),
    modules: [pathConfig.appSrc, pathConfig.appNodeModules]
  },
  module: {
    rules: [
      {
        oneOf: [
          {
            test: /route\.js$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  cacheDirectory: true,
                  presets: [
                    [
                      '@babel/preset-env',
                      {
                        targets: '> 0.25%, not dead'
                      }
                    ],
                    '@babel/preset-react'
                  ],
                  plugins: [
                    [
                      '@babel/plugin-transform-runtime',
                      {
                        helpers: false,
                        regenerator: true,
                        useESModules: true
                      }
                    ],
                    '@babel/plugin-syntax-dynamic-import',
                    ['@babel/plugin-proposal-decorators', { legacy: true }],
                    ['@babel/plugin-proposal-class-properties', { loose: true }],
                    ['import', { libraryName: 'antd', style: true }]
                  ]
                }
              },
              {
                loader: './config/loader/transformer'
              },
              'lodash'
            ]
          },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'thread-loader',
                options: {
                  workers: 4
                }
              },
              {
                loader: 'babel-loader',
                options: {
                  cacheDirectory: true,
                  presets: ['@babel/preset-env', '@babel/preset-react'],
                  plugins: [
                    ['@babel/plugin-proposal-optional-chaining'],
                    [
                      '@babel/plugin-transform-runtime',
                      {
                        helpers: false,
                        regenerator: true,
                        useESModules: true
                      }
                    ],
                    '@babel/plugin-syntax-dynamic-import',
                    ['@babel/plugin-proposal-decorators', { legacy: true }],
                    ['@babel/plugin-proposal-class-properties', { loose: true }],
                    ['import', { libraryName: 'antd', style: true }]
                  ]
                }
              },
              'lodash'
            ]
          },
          {
            test: /\.(bmp|png|svg|jpg|jpeg|gif)$/,
            use: {
              loader: 'url-loader',
              options: {
                limit: 10000,
                name: 'static/media/[name].[hash:8].[ext]'
              }
            }
          },
          {
            test: /\.css$/,
            use: [
              'style-loader',
              {
                loader: 'css-loader',
                options: {
                  importLoaders: 1
                }
              },
              {
                loader: 'postcss-loader',
                options: {
                  plugins: [require('autoprefixer')]
                }
              }
            ]
          },
          {
            test: /\.less$/,
            use: [
              {
                loader: 'style-loader'
              },
              {
                loader: 'css-loader',
                options: {
                  importLoaders: 2
                }
              },
              {
                loader: 'postcss-loader',
                options: {
                  plugins: [require('autoprefixer')]
                }
              },
              {
                loader: 'less-loader',
                options: { modifyVars, javascriptEnabled: true }
              }
            ]
          },
          {
            test: /\.(woff|woff2|eot|ttf|otf)$/,
            use: {
              loader: 'file-loader',
              options: {
                name: 'static/font/[name].[hash:8].[ext]'
              }
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new LodashModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(VERSION),
      ENABLE_REDUX_LOG: ENABLE_REDUX_LOG,
      DEPLOY_TIME: DEPLOY_TIME,
      ENVIRONMENT: JSON.stringify('dev')
    }),
    new CopyWebpackPlugin([pathConfig.appPublic]),
    new HtmlWebpackPlugin({
      template: pathConfig.appHtml,
      chunks: ['app']
    }),
    new HtmlWebpackPlugin({
      template: pathConfig.appHtml,
      filename: 'updating.html',
      chunks: ['updating']
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DllReferencePlugin({
      manifest: path.resolve(__dirname, 'vendor/vendor-manifest.json')
    }),
    new AddAssetHtmlPlugin([
      {
        filepath: require.resolve(path.resolve(__dirname, 'vendor/vendor.dll.js'))
      }
    ])
  ],
  devServer: {
    ...devServerSource,
    host: HOST,
    contentBase: path.resolve(__dirname, 'build'),
    hot: true,
    clientLogLevel: 'none',
    historyApiFallback: true
  },
  devtool: 'cheap-module-eval-source-map',
  performance: {
    hints: false
  }
};
